package com.example.springcloud.controller;

import com.example.springcloud.pojo.Dept;
import com.example.springcloud.service.DeptService;
import com.netflix.hystrix.contrib.javanica.annotation.HystrixCommand;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cloud.client.ServiceInstance;
import org.springframework.cloud.client.discovery.DiscoveryClient;
import org.springframework.web.bind.annotation.*;

import java.util.List;

/**
 * @author :lihao
 * @date :2020/12/1
 * @description : Hystrix熔断器
 */
@RestController
public class DeptController {

    /**
     * 注入服务
     */
    @Autowired
    private DeptService deptService;

    /**
     * 通过部门id查询部门
     * @param id 部门id
     * @return 部门信息
     * @description id查询结果为null时，触发熔断，调用备选方法
     */
    @GetMapping("/dept/get/{id}")
    @HystrixCommand(fallbackMethod = "hystrixGetDept")
    public Dept getDept(@PathVariable("id") Long id) {
        Dept dept = deptService.queryDeptById(id);
        if (dept == null) {
            throw new RuntimeException("查询信息为空");
        }
        return dept;
    }

    /**
     * 备选方法
     * 当服务发生熔断时调用该方法
     */
    public Dept hystrixGetDept(@PathVariable("id") Long id) {
        return new Dept()
                .setDeptNo(id)
                .setDeptName("not have DeptName,this is @Hystrix")
                .setDbSource("no this database in MySql");
    }
}
